﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace ValidationFramework.WPF
{
    /// <summary>
    /// Represents the converter that converts <see cref="Enum"/> values to and from <see cref="Visibility"/> enumeration values.
    /// </summary>
#if (!SILVERLIGHT)
    [ValueConversion(typeof(bool), typeof(object))]
#endif
    public class EnumToVisibilityValueConverter : IValueConverter
    {
        /// <inheritdoc />
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //Type underlyingType = Nullable.GetUnderlyingType(targetType);
            //if ((targetType != typeof(Enum)) || (underlyingType != null && underlyingType != typeof(Enum)))
            //{
            //    throw new ArgumentException("Type must be a enum", "targetType");
            //}
            if (value == null)
            {
                if (parameter == null)
                {
                    return Visibility.Visible;
                }
                else
                {
                    return Visibility.Collapsed;
                }
            }
            if (value.ToString() == (string)parameter)
            {
                return Visibility.Visible;
            }
            else
            {
                return Visibility.Collapsed;
            }

        }

        /// <inheritdoc />
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var enumType = Nullable.GetUnderlyingType(targetType);
            if (enumType == null)
            {
                enumType = targetType;
            }
            return Enum.Parse(enumType, (string)parameter, true);
        }
    }
}
